<template>
  <div class="user-list">
    <h4>用户列表</h4>
    <!-- 搜索部分 -->
    <div class="search">
      <el-input
        placeholder="请输入内容"
        @input="handleInput"
        v-model="keywords"
        class="input-with-select"
      >
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input>
      <el-button type="primary" @click="openModal">添加用户</el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="cutList" border style="width: 100%">
     <el-table-column
      label="#"
      type="index"
      width="50">
    </el-table-column>
      <el-table-column fixed prop="username" label="姓名">
      </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="mobile" label="电话">
      </el-table-column>
      <el-table-column prop="role_name" label="角色"> </el-table-column>
      <el-table-column prop="create_time" label="注册时间">
          <template slot-scope="scope">
             {{scope.row.create_time | filterTime}}
          </template>
      </el-table-column>
      <el-table-column prop="mg_state" label="状态"> 
        <!-- @change="(val)=>handleChange(val,scope.row)"  这种写法即保留自带的回调参数，又可以传递自己的参数 -->
        <template slot-scope="scope">
            <el-switch
            v-model="scope.row.mg_state"
            @change="(val)=>handleChange(val,scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949">
            </el-switch>
        </template>
      </el-table-column>
      <el-table-column  label="操作">
        <template slot-scope="scope">
         
          <el-button type="primary" circle  size="small" @click="handleEdit(scope.row)" icon="el-icon-edit">
            
          </el-button>
          <el-button type="danger" circle  size="small" @click="handleDelete(scope.row.id)" icon="el-icon-delete">
            
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 模态框 -->
    <!-- .sync 修饰符  -->
    <el-dialog
        :title="ruleForm.id?'编辑用户':'添加用户'"
        :visible.sync="dialogVisible"
        width="40%"
       >
        <!-- 表单 -->
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="ruleForm.username" :disabled="Boolean(ruleForm.id)"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" v-if="!ruleForm.id">
                <el-input v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="ruleForm.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
                <el-input v-model="ruleForm.mobile"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submit">{{ruleForm.id?'编辑':'添加'}}</el-button>
        </span>
        </el-dialog>

        <!-- 分页 -->
        <!-- @size-change 每页条数改变触发 -->
        <!-- @current-change当前页面改变触发 -->
        <!-- sync修饰符 -->
         <el-pagination
            @size-change="handleCurrentChange"
            @current-change="handleCurrentChange"
            :current-page.sync="pageNum"
            :page-sizes="[1, 3, 6, 9]"
            :page-size.sync="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
  </div>
</template>
<script>
import axios from "axios";
import moment from 'moment'
export default {
  data() {
    return {
      keywords: "", //搜索的关键字
      dialogVisible:false,//模态框的状态
      ruleForm:{},//表单数据
      rules: {
          username: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
          ],
           password: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
          ],
           email: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
          ],
           mobile: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
          ],
    },
    total:0,//总条数
    pageNum:1,//当前页
    pageSize:3,//每页放多少条
    cutList:[],//截取分页后的数组
    time:null,

    };
  },
  created() {
    // 加一层判断 如果vuex的数据为空，才去请求数据
    if(!this.$store.state.userList.length){
        this.getUserList();
    }else{
        this.handleCurrentChange()
    }
  },
  methods: {
    // 获取json里面的数据
    getUserList() {
      axios.get("userlist.json").then((res) => {
        console.log(res);
        
        this.total = res.data.data.total
        this.handleCurrentChange()
        this.$store.commit("setUserList", res.data.data.users);
      });
    },
    // 点击添加按钮的事件
    openModal(){
        this.dialogVisible = true
        // 点击添加的时候，及时每次清楚ruleForm.id
        this.ruleForm.id = ''
        // 情况表单
        this.ruleForm = {}
    },
    // 点击确定按钮
    submit(){
         this.$refs["ruleForm"].validate((valid) => {
          if (valid) {
            // 校验通过
            if(this.ruleForm.id){
                // 编辑
                this.$store.commit('editUser',this.ruleForm)
            }else{
                //  添加
                 this.$store.commit('addUser',this.ruleForm)
            }
            // 关闭模态框
            this.dialogVisible = false
             //   调用分页函数
          this.handleCurrentChange()
            
          } else {
            // 校验不通过
            alert('校验不通过')
            return false;
          }
        });
    },
    handleChange(val,row){
        console.log(val);
        console.log(row);
        this.$store.commit('handleChange',row)

    },
    handleEdit(row){
        this.dialogVisible = true
        this.ruleForm = row
    },
    // 删除
    handleDelete(id){
    //    友情提示
     this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            // 确定按钮
            this.$store.commit('handleDel',id)
           this.$message({
            type: 'success',
            message: '删除成功!'
          });
        //   调用分页函数
          this.handleCurrentChange()
         
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    //  分页
    handleCurrentChange(){

        // 搜索的逻辑
         let resList =  this.$store.state.userList.filter(item=>item.username.includes(this.keywords))
        this.total = resList.length

        //  this.total = this.$store.state.userList.length
 
    //     获取截取的头部 位置  (this.pageNum-1)*this.pageSize
    //    获取截取的尾部位置   this.pageNum* this.pageSize
        let start = (this.pageNum-1)*this.pageSize
        let end = this.pageNum* this.pageSize
        this.cutList = resList.slice(start,end)   
    },
    // 搜索框的input事件  防抖
    handleInput(){
        console.log(this.keywords);
        // 清除没有执行的定时器，留下时间间隔内的最后一次
        if(this.time){
            clearTimeout(this.time)
        }
        this.time = setTimeout(()=>{
            console.log(this.keywords);
            this.handleCurrentChange()
        },1000)
    }
  },
  filters:{
    filterTime(val){
           moment.locale('zh-cn') //设置语言
        return moment(val).format('YYYY:MM:DD hh:mm:ss a')

    }
  }
};
</script>
<style lang="scss" scoped>
.search {
  display: flex;
  margin: 10px;
  .el-input {
    width: 500px;
  }
}
</style>
